package netssl;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.*;
import java.security.cert.CertificateException;

public class J_SSLServerAlias {
    public static void main(String[] args){
        String keystorepath = "F:\\temp\\new.keystore";
        String keypass = "123456";
        String alias = "newmark";
        //指定密钥库和密码
        System.setProperty("Self.alias",alias);
        System.setProperty("Self.keypass",keypass);

        try {
            Security.addProvider(new J_SelfProvider());  //添加新的安全提供者
            SSLContext sc = SSLContext.getInstance("SSL");
            KeyStore ks = KeyStore.getInstance("JKS");
            char password[] = keypass.toCharArray();

            //加载密钥库
            ks.load(new FileInputStream(keystorepath),password);

            //获取服务器端套接字工厂的实例对象
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("Self");
            kmf.init(ks,password);
            sc.init(kmf.getKeyManagers(),null,null);
            SSLServerSocketFactory ssf = sc.getServerSocketFactory();

            //创建服务器端套接字
            SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(5000);
            int i = 0;
            while (true){
                System.out.println("["+(++i)+"]:等待来自客户端的连接......");
                //监听并等待来自客户端的连接
                Socket s = ss.accept();
                PrintWriter pw = new PrintWriter(s.getOutputStream());
                InetAddress sa = s.getInetAddress();
                InetAddress ca = s.getLocalAddress();
                System.out.println("服务器端向客户端发送信息：");
                String str = "来自"+ca.getHostAddress()+"("+s.getLocalPort()+")"+"向"+sa.getHostAddress()+"("+s.getPort()+")发送的问候";
                System.out.println(str);
                pw.println(str);
                pw.flush();

                System.out.println("服务器端接收客户端信息：");
                BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                str = br.readLine();
                System.out.println(str);

                br.close();
                pw.close();
                s.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }
}
